package net.xujialiang.XTestRPA.Service;

import net.xujialiang.XTestRPA.Entity.XRPALog;
import net.xujialiang.XTestRPA.Repository.LogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class XRPALogService {

    @Autowired
    LogRepository logRepository;

    public void addLog(String module, String action, String createAccount, String ttc) throws Exception {
        XRPALog entity = XRPALog.builder()
                .account(createAccount)
                .action(action)
                .module(module)
                .ttc(ttc)
                .optime(new Timestamp(System.currentTimeMillis()))
                .build();
        logRepository.save(entity);
    }

    public Map<String, Object> fetch(String module, String ttc, String account, int page, int pageSize){
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest pr =  PageRequest.of(page,pageSize, sort);
        Page<XRPALog> pageData;
//        if(module == null || module.equals("")){
//            pageData = logRepository.findByTtc( ttc, pr);
//        }else{
//            pageData = logRepository.findByTtcAndModule( ttc, module, pr);
//        }
        if(module.equals("")){
            module = null;
        }
        if(account.equals("")){
            account = null;
        }
        pageData = logRepository.findByTtcAndModuleAndAccount(ttc,module, account, pr);

        Map<String, Object> ret = new LinkedHashMap<>();
        ret.put("totalPages", pageData.getTotalPages());
        ret.put("totalCount", pageData.getTotalElements());
        ret.put("page", page);
        ret.put("pageSize", pageSize);
        ret.put("list", pageData.getContent());
        return ret;
    }
}
